﻿using System;
using System.Collections.Generic;
using System.Text;
using Gbu.BLTool.Entitys;
using RestSharp;
using RestSharp.Deserializers;
using JsonSerializer = RestSharp.Serializers.JsonSerializer;
using System.Linq;

namespace Gbu.BLTool.BaseTool
{
    public class CommRestClient
    {

        public void Call<TReq,TRet>(CommRequestEntity<TReq> requestEntity, Action<CommResponseEntity<TRet>> callback)
            where TRet : new()
        {
            var client = new RestClient(requestEntity.ReqBaseUrl);
           

            var req = new RestRequest(requestEntity.ReqName, requestEntity.ReqMethod);
            req.AddHeader("accept", "text/json");
            var js = new JsonSerializer();
            var para = js.Serialize(requestEntity.ReqParam);
            

            var paramList = EntityTool.GetProperties(requestEntity.ReqParam);
            foreach (var p in paramList)
            {
                if (p.Type == ParameterType.UrlSegment)
                {
                    req.AddUrlSegment(p.Name, p.Value.ToString());
                }
                else { req.AddParameter(p); }
                
            }
            //req.AddBody(para);
           // req.AddParameter("json", "true");
            client.ExecuteAsync(req, (restRespon, handler) =>
            {
                var jd = new JsonDeserializer();
                var ret=new CommResponseEntity<TRet>();
                try
                {
                    ret = jd.Deserialize<CommResponseEntity<TRet>>(restRespon);
                }
                catch (Exception ex)
                {
                    ret.MessageCode=-1;
                    ret.Status = -1;
                    ret.Message = ex.Message;
                }
                //var ret = jd.Deserialize<CommResponseEntity<TRet>>(restRespon);
                if (callback != null)
                {
                    callback(ret);
                }
                handler.Abort();
            });
        }
    }
}
